<?php

namespace App\Morefun\Prize;

use App\Entities\VoucherCode;
use App\Morefun\SerialNumber\Generator;
use Illuminate\Container\Container;

class EntityCodeSynchronizer
{
    public function generateCodes($number)
    {
        $number += 0;

        if ($number <= 0) {
            return [];
        }

        $codes = [];
        $channel = Generator::channel('prize.entity');

        for ($times = 0; $times <= $number; ++$times) {
            $codes[] = $channel->generate();
        }

        return $codes;
    }

    public function save($prizeId, array $codes)
    {
        $values = [];

        foreach ($codes as $code) {
            $values[] = [
                'prize_id' => $prizeId,
                'code' => $code,
                'granted' => 0,
            ];
        }

        return VoucherCode::query()->insert($values);
    }

    public function writeToRedis($prizeId, array $codes)
    {
        $redis = Container::getInstance()->make('redis');
        $key = sprintf('voucher:codes:%s', $prizeId);

        foreach ($codes as $code) {
            $redis->sadd($key, $code);
        }
    }
}
